package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.Reserve;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 根据预约id查询预约信息
     * @param id
     * @return
     */
    @PostMapping("/findById")
    public Result findById(String id){
        try{
            log.info("查询到预约：{}",id);
            Order order =  orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,order);
        }catch (Exception e){
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 体检预约
     * @param reserve
     * @return
     */
    @PostMapping("/submitOrder")
    public Result submitOrder(@RequestBody Reserve reserve){
        String telephone = reserve.getTelephone();

        // 从redis缓存中获取验证码
        String RedisOfCode = redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = reserve.getValidateCode();

        // 校验用户输入的验证码是否正确
        if (RedisOfCode == null || !RedisOfCode.equals(validateCode)){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

        try {
            log.info("体检预约：{}",reserve);
            Result result = orderService.submitOrder(reserve);
            return new Result(true,MessageConstant.ORDER_SUCCESS,result);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "预约失败: " + e.getMessage());
        }
    }
}
